/**
 * 双击文本框进行编辑
 * @param element
 */
function editScData(element) {
    var oldhtml = element.innerHTML;
    //创建新的input元素
    var newobj = document.createElement('input');
    //为新增元素添加name属性，属性值为前一个td的name
    newobj.name = element.name;
    //为新增元素添加类型
    newobj.type = 'text';
    //为新增元素添加value值
    newobj.value = oldhtml;
    //为新增元素添加光标离开事件
    newobj.onblur = function() {
        element.innerHTML = this.value == oldhtml ? oldhtml : this.value;
        //当触发时判断新增元素值是否为空，为空则不修改，并返回原有值
    }
    //设置该标签的子节点为空
    element.innerHTML = '';
    //添加该标签的子节点，input对象
    element.appendChild(newobj);
    //设置选择文本的内容或设置光标位置（两个参数：start,end；start为开始位置，end为结束位置；如果开始位置和结束位置相同则就是光标位置）
    newobj.setSelectionRange(0, oldhtml.length);
    //设置获得光标
    newobj.focus();
}

/**
 * 保存编辑的生产数据信息
 * @param orderId:订单ID；  busType:业态类型
 */
function saveOrderscData(orderId,busType) {
    var count = 0;
    $.each($('[checkData = "isIntGteZero"]'), function (i, e) {
        var flag = isIntGteZero(e);
        if (!flag) {
            count++
        }
        ;
    })
    $.each($('[checkData = "isHref"]'), function (i, e) {
        var flag = isHref(e);
        if (!flag) {
            count++
        }
        ;
    })
    $.each($('[checkData = "isEmail"]'), function (i, e) {
        var flag = isEmail(e);
        if (!flag) {
            count++
        }
        ;
    })
    $.each($('[isSiding]'), function (i, e) {
        e = $(e);
        var rule = e.attr("isSiding");
        var arr = rule.split(",");
        var flag = isSiding(e, arr);
        if (!flag) {
            count++
        }
        ;
    })
    $.each($('[checkData = "isDay"]'), function (i, e) {
        var flag = isDay(e);
        if (!flag) {
            count++
        }
        ;
    })


    if (count > 0) {
        return;
    }
    var formName = "orderForm" + orderId;
    var orderId = orderId;
    var busType = busType;
    var data=$("form[name=" + formName + "]").serialize();
    $.ajax({
        type: "post",
        data: data,
        dataType: "json",
        url: sysInfo.basePath + "/sc/general/scData/update/data.do",
        success: function (result) {
            if (result.code == 0) {
                DGG.Layer.message('修改成功', {icon: '1'});

            }
            else {
                DGG.Layer.message('修改失败', {icon: '2'}, function () {
                    flushParentIframe();
                });
            }
        }

    });

}


//三方卡编辑弹窗
function otherCard() {
    layer.open({
        type: 1,
        title: "编辑三方卡",
        skin: 'layui-layer-rim', //加上边框
        area: ['25%', '35%'], //宽高
        shadeClose: true,
        content: $('#layer_thirdCard'),
        btn: ['确定','取消'],
        btnAlign: 'c',
        yes:function() {
            callbackdata();
        },
        cancel: function () {
            $("#layer_thirdCard").hide();
            $("#layer_numberAndPwd").hide();
        },
        btn2: function () {
            $("#layer_thirdCard").hide();
            $("#layer_numberAndPwd").hide();
        }
        });
}
function callbackdata() {
    var name = $("#thirdCardName").val();
    var number = $("#thirdCardNum").val();
    $("#otherCardStr").html(name + ":" + number);
    $("#thirdpartyName").val(name);
    $("#thirdpartyNumber").val(number);
    layer.closeAll();
    $("#layer_thirdCard").hide();
    $("#layer_numberAndPwd").hide();

}

//编辑账号和密码
function editNumberAndPwd() {
    layer.open({
        type: 1,
        title: "编辑账号/密码",
        skin: 'layui-layer-rim', //加上边框
        area: ['25%', '65%'],//宽高
        shadeClose: true,
        content: $('#layer_numberAndPwd'),
        btn: ['确定','取消'],
        btnAlign: 'c',
        yes:function() {
            callbackdata();
        },
        cancel: function () {
            $("#layer_thirdCard").hide();
            $("#layer_numberAndPwd").hide();
        },
        btn2: function () {
            $("#layer_thirdCard").hide();
            $("#layer_numberAndPwd").hide();
        }
    });
}

//刷新当前iframe页面
function flushParentIframe() {
    /*document.getElementById('scNodeDataIframe').contentWindow.location.reload(true);*/
    //刷新节点
    parent.refreshNode();
}


/*
 *新增产品弹框
 * scProId:生产子订单id
 */
function addProduct(scProId) {
    DGG.Layer.open(sysInfo.basePath + "/sc/general/scBaseInfo/scAddProduct.do?id=" + scProId, {
        title: '新增产品',
        area: ['85%', '60%'],
        btn: ""
    });
}

/*
 *查询当前业态下的产品和商品
 */
function getProduct(proType, txt) {
    $("#templateTable td[name='busTypeName']").html(txt);
    if (proType == undefined || proType == "" || proType == null) {
        DGG.Layer.message('请先选择业务类型', {icon: '2'});
    } else {
        $("#productId").empty();
        $("#goodsId").empty();
        $.ajax({
            type: "post",
            data: {proType: proType},
            url: sysInfo.basePath + "/sc/general/com/find_product.do",
            success: function (data) {
                var productStr = "";
                var goodsStr = "";
                productStr += '<option value="">请选择</option>';
                goodsStr += '<option value="">请选择</option>';
                if (data.length >= 1) {
                    for (var i = 0; i < data.length; i++) {
                        var item = data[i];
                        var opt = '<option  value="' + item.id + '" data-code="' + item.belongName + '" product-name="' + item.name + '" channel-name="' + (item.channelNames==null?"":item.channelNames) + '">' + item.name + '</option> ';
                        //追加一个option
                        productStr += opt;
                    }
                }
                $("#productId").append(productStr);
                $("#goodsId").append(goodsStr);
            }
        });

    }

}

function getGoods() {
    var belongName = $("#productId option:selected").attr("data-code");
    $("#templateTable td[name='belongName']").html(belongName);
    var proName = $("#productId option:selected").attr("product-name");
    $("#templateTable td[name='productName']").html(proName);
    var channel = $("#productId option:selected").attr("channel-name");
    $("#templateTable td[name='channelNames']").html(channel);
    var productId = $("#productId").val();
    $("input[name='seriproductId']", $("#templateTable")).val(productId);
    var proId = $("#productId").val();
    if (proId == undefined || proId == "" || proId == null) {
        DGG.Layer.message('请先选择产品', {icon: '2'});
    } else {
        $("#goodsId").empty();
    $.ajax({
        type: "post",
        data: {proId: proId},
        url: sysInfo.basePath + "/sc/general/com/find_goods.do",
        success: function (data) {//map:goodsList
            var goodsStr = "";
            var result = data.goodsList;
            goodsStr += '<option value="">请选择</option>';
            if (result.length >= 1) {
                for (var i = 0; i < result.length; i++) {
                    var item = result[i];
                    var opt = '<option  value="' + item.id + '" data-code="' + item.goodsAttribute + '">' + item.proName + "-" + item.goodsAttribute + '</option> ';
                    //追加一个option
                    goodsStr += opt;
                }
            }
            $("#goodsId").append(goodsStr);
        }
    });
    }

}

//确认新增
function confirmAdd() {
    $.each($('[isSiding]'), function (i, e) {
        e = $(e);
        var rule = e.attr("isSiding");
        var arr = rule.split(",");
        var flag = isSiding(e, arr);
        if (!flag) {
            count++
        }
        ;
    })
    var arr = new Array();
    $("#myTable").find("tr.templateTr").each(function (i, e) {
        var obj = $(e).serialize2object({extra: "td"});
        arr.push(obj);
    });
    if (arr.length == 0) {
        DGG.Layer.message('暂无数据', {icon: '0'});
        return;
    }
    DGG.Layer.loading.start();
    $.ajax({
        type: "post",
        data: {params: JSON.stringify(arr)},
        url: sysInfo.basePath + "/sc/general/com/addProductData.do",
        success: function (result) {
            DGG.Layer.loading.done();
            if (result.code == 0) {
                DGG.Layer.message('新增成功', {icon: '1'}, function () {
                    closeTabel();
                });
            }
            else {
                DGG.Layer.message(result.msg, {icon: '2'}, function () {
                    closeTabel();
                });
            }
        }
    });
}

/**
 * 将表单元素序列化成一个属性对象
 * @param options 可用序列化参数：
 * {
     * allowEmpty:false,
     * includeHidden:true,
     * trimString:true
     * }
 * @return object
 */
$.fn.serialize2object = function (options) {
    var setting = {};
    setting.allowEmpty = false;//序列化空值
    setting.includeHidden = true;//序列化隐藏值
    setting.trimString = true;//trim值
    setting.extra = undefined;//额外序列化标签
    setting.base = "input,select,textarea";//序列化标签
    $.extend(setting, options);
    var data = {};
    var tags = setting.base;
    if (setting.extra != undefined) {
        tags = tags + "," + setting.extra;
    }
    var items = $(this).find(tags);
    if (items.size() == 0) {
        console.log("no filed found in this container");
        return data;
    }
    items.each(function (i, e) {
        var item = $(e);
        var hidden = item.css("display") == "none";
        var name = item.attr("name");
        //没有name属性不序列化
        if (name == undefined || name == "") return;
        var baseTags = setting.base.split(",");
        var isBase = false;
        for (var i = 0; i < baseTags.length; i++) {
            if (item.is(baseTags[i])) {
                isBase = true;
                break;
            }
        }
        var value;
        if (isBase) {
            value = item.val();
        }
        else {
            value = item.text();
        }
        //配置要求隐藏元素不序列化
        if (hidden && !setting.includeHidden) return;
        //控件值异常不序列化
        if (value == undefined) return;
        value = value.trim();
        //配置要求空值不序列化
        if (value == "" && setting.allowEmpty == false) return;
        data[name] = value;
    });
    for (var key in data) {
        var value = data[key];
        //去掉字符串前后的空格
        if (setting.trimString) {
            value = typeof(value) == "string" ? value.trim() : value;
            data[key] = value;
        }
        value = data[key];
        //是否允许空值
        if (!setting.allowEmpty && value == "") {
            delete data[key];
        }
    }
    return data;
}

//关闭
function closeTabel() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

//是否可以编辑
function canEdit() {
    $(".canEditData td input").removeAttr('disabled');
    $(".canEditData td select").removeAttr('disabled');
    $(".canEditData td a").css('pointerEvents', "auto");
    $(".canEditData").removeClass('canEditData');


}

